/*
 * @Description: 更新日志表格组件
 * @Author: Rfan
 * @Date: 2022-06-11 09:59:07
 * @LastEditTime: 2022-06-11 15:18:57
 */

import { useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { useChangeLogContext } from '../contexts/ChangeLogContext';
import { formatDate } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import EditDialog from './dialogs/EditDialog';

const { Column } = Table;

const List = () => {
  const formatMessage = useFormatMessage();

  const { list, loading, onDeleteChangeLog } = useChangeLogContext();

  // 选中的单位
  const [selectItem, setSelectItem] = useState<any>({});
  // 编辑弹窗显示状态
  const [editVisible, setEditVisible] = useState(false);

  const showEditModal = (data: any) => {
    setSelectItem(data);
    setEditVisible(true);
  };

  return (
    <>
      <Table dataSource={list} loading={loading} rowKey="id" bordered>
        <Column title="ID" dataIndex="id" key="id" align="center" width={100} />
        <Column title="版本" dataIndex="updateVersion" key="updateVersion" align="center" />
        <Column
          title="更新时间"
          dataIndex="updateTime"
          key="updateTime"
          align="center"
          render={(text) => formatDate(text, 'YYYY-MM-DD')}
        />
        <Column
          title="更新项目数量"
          dataIndex="updateInfoList"
          key="updateInfoList"
          align="center"
          render={(text) => text?.length || 0}
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                onClick={() => {
                  showEditModal(record);
                }}
              >
                编辑
              </Button>
              <Button
                type="link"
                danger
                onClick={() => {
                  onDeleteChangeLog(record.id);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
      </Table>

      {/* 编辑弹窗 */}
      {useMemo(
        () => (
          <EditDialog
            visible={editVisible}
            data={selectItem}
            onClose={() => {
              setEditVisible(false);
            }}
          />
        ),
        [editVisible]
      )}
    </>
  );
};

export default List;
